package com.yunma.dialog;

import com.chanjet.unbindmobile.UnbindMobile;
import com.common.util.SystemHWUtil;
import com.http.bean.HttpRequestParameter;
import com.http.bean.HttpResponseResult;
import com.http.util.HttpSocketUtil;
import com.io.hw.json.JSONHWUtil;
import com.string.widget.util.ValueWidget;
import com.swing.component.AssistPopupTextField;
import com.swing.component.AssistPopupTextPane;
import com.swing.component.ComponentUtil;
import com.swing.dialog.DialogUtil;
import com.swing.dialog.GenericDialog;
import com.swing.dialog.toast.ToastMessage;
import com.swing.messagebox.GUIUtil23;
import com.yunma.bean.UnbindMobileBean;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class UnbindMobileDialog extends GenericDialog implements ItemListener {

    public static final String CIA_DOMAIN_INTE = "inte-cia.chanapp.chanjet.com";
    public static final String CIA_DOMAIN_PROD = "cia.chanapp.chanjet.com";
    private static final long serialVersionUID = 118696936195795933L;
    private static SimpleAttributeSet HTML_RED = new SimpleAttributeSet();
    private static SimpleAttributeSet HTML_GREEN = new SimpleAttributeSet();

    static {
        StyleConstants.setForeground(HTML_RED, Color.red);
        StyleConstants.setBold(HTML_RED, true);
//		    StyleConstants.setItalic(HTML_RED, true);//斜体
//		    StyleConstants.setFontFamily(HTML_RED, "Helvetica");
        StyleConstants.setFontSize(HTML_RED, 18);

        StyleConstants.setForeground(HTML_GREEN, Color.GREEN);
        StyleConstants.setBold(HTML_GREEN, true);
        StyleConstants.setFontSize(HTML_GREEN, 16);
    }

    private JPanel contentPane;
    private AssistPopupTextField mobileTextField;
    private AssistPopupTextField codeTextField;
    private AssistPopupTextField ciaIpTextField;
    private UnbindMobileBean unbindMobileBean;
    private JRadioButton inteRadioButton;
    private JRadioButton productRadioButton;
    private AssistPopupTextPane noteTextPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UnbindMobileDialog frame = new UnbindMobileDialog();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public void layout3(Container contentPane) {
        setModal(true);
//		setBounds(100, 100, 450, 600);
        setLoc(450, 360);
        setTitle("解绑手机号");
//		contentPane = new JPanel();
//		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.CENTER);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[]{0, 0, 0, 0, 0, 0};
        gbl_panel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
        gbl_panel.columnWeights = new double[]{0.0, 0.0, 1.0, 0.0, 0.0, Double.MIN_VALUE};
        gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        panel.setLayout(gbl_panel);

        ciaIpTextField = new AssistPopupTextField();
        ciaIpTextField.placeHolder("cia域名");
//        ciaIpTextField.setEditable(false);
        final String ciaDomain;
        if (ValueWidget.isNullOrEmpty(getUnbindMobileBean()) || ValueWidget.isNullOrEmpty(getUnbindMobileBean().getCiaDomain())) {
            ciaDomain = CIA_DOMAIN_INTE;
        } else {
            ciaDomain = getUnbindMobileBean().getCiaDomain();
        }
        ciaIpTextField.setText(ciaDomain);
        ciaIpTextField.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        decideRadioSelected();
                    }
                }).start();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        decideRadioSelected();
                    }
                }).start();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        decideRadioSelected();
                    }
                }).start();
            }
        });

        GridBagConstraints gbc_ciaIpTextField = new GridBagConstraints();
        gbc_ciaIpTextField.insets = new Insets(0, 0, 5, 5);
        gbc_ciaIpTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_ciaIpTextField.gridx = 2;
        gbc_ciaIpTextField.gridy = 0;
        panel.add(ciaIpTextField, gbc_ciaIpTextField);
        ciaIpTextField.setColumns(10);

        JPanel panel_2 = new JPanel();
        GridBagConstraints gbc_panel_2 = new GridBagConstraints();
        gbc_panel_2.gridwidth = 4;
        gbc_panel_2.insets = new Insets(0, 0, 5, 5);
        gbc_panel_2.fill = GridBagConstraints.BOTH;
        gbc_panel_2.gridx = 0;
        gbc_panel_2.gridy = 1;
        panel.add(panel_2, gbc_panel_2);

        inteRadioButton = new JRadioButton("集测");
        inteRadioButton.addItemListener(this);
        panel_2.add(inteRadioButton);

        productRadioButton = new JRadioButton("生产环境");
        productRadioButton.addItemListener(this);
        panel_2.add(productRadioButton);

        decideRadioSelected();

        ButtonGroup btnGroup = new ButtonGroup();
        btnGroup.add(inteRadioButton);
        btnGroup.add(productRadioButton);

        JLabel label = new JLabel("手机号");
        GridBagConstraints gbc_label = new GridBagConstraints();
        gbc_label.anchor = GridBagConstraints.WEST;
        gbc_label.insets = new Insets(0, 0, 5, 5);
        gbc_label.gridx = 0;
        gbc_label.gridy = 2;
        panel.add(label, gbc_label);

        mobileTextField = new AssistPopupTextField();
        if (!ValueWidget.isNullOrEmpty(getUnbindMobileBean())) {
            mobileTextField.setText(getUnbindMobileBean().getMobile());
        }

        mobileTextField.placeHolder("手机号");
        GridBagConstraints gbc_mobileTextField = new GridBagConstraints();
        gbc_mobileTextField.insets = new Insets(0, 0, 5, 5);
        gbc_mobileTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_mobileTextField.gridx = 2;
        gbc_mobileTextField.gridy = 2;
        panel.add(mobileTextField, gbc_mobileTextField);
        mobileTextField.setColumns(10);

        final JButton isRegisterbutton = new JButton("是否占用");
        GridBagConstraints gbc_isRegisterbutton = new GridBagConstraints();
        gbc_isRegisterbutton.insets = new Insets(0, 0, 5, 5);
        gbc_isRegisterbutton.gridx = 3;
        gbc_isRegisterbutton.gridy = 2;
        panel.add(isRegisterbutton, gbc_isRegisterbutton);
        isRegisterbutton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!DialogUtil.verifyTFEmpty(mobileTextField, "手机号")) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        isRegisterbutton.setEnabled(false);
                        try {
                            checkUserIdentify(isRegisterbutton);
                        } catch (Exception e1) {
                            isRegisterbutton.setEnabled(true);
                            e1.printStackTrace();
                        }
                    }
                }).start();
            }
        });

        JLabel label_1 = new JLabel("短信验证码");
        GridBagConstraints gbc_label_1 = new GridBagConstraints();
        gbc_label_1.anchor = GridBagConstraints.WEST;
        gbc_label_1.insets = new Insets(0, 0, 5, 5);
        gbc_label_1.gridx = 0;
        gbc_label_1.gridy = 3;
        panel.add(label_1, gbc_label_1);

        codeTextField = new AssistPopupTextField();
        codeTextField.placeHolder("短信验证码");
        GridBagConstraints gbc_codeTextField = new GridBagConstraints();
        gbc_codeTextField.insets = new Insets(0, 0, 5, 5);
        gbc_codeTextField.fill = GridBagConstraints.HORIZONTAL;
        gbc_codeTextField.gridx = 2;
        gbc_codeTextField.gridy = 3;
        panel.add(codeTextField, gbc_codeTextField);
        codeTextField.setColumns(10);

        final JButton sendButton = new JButton("发短信");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!DialogUtil.verifyTFEmpty(mobileTextField, "手机号")) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            sendButton.setEnabled(false);
                            boolean success = UnbindMobile.sendCode(mobileTextField.getText2().trim(), ciaIpTextField.getText2());
                            sendButton.setEnabled(true);
                            if (success) {
                                ToastMessage.toast("操作成功", 2000);
                            } else {
                                ToastMessage.toast("操作失败(可能手机号并未绑定)", 2000, Color.red);
                            }
                        } catch (IOException e1) {
                            e1.printStackTrace();
                            GUIUtil23.errorDialog(e1.getMessage());
                            sendButton.setEnabled(true);
                        }
                    }
                }).start();
            }
        });
        GridBagConstraints gbc_sendButton = new GridBagConstraints();
        gbc_sendButton.insets = new Insets(0, 0, 5, 5);
        gbc_sendButton.gridx = 3;
        gbc_sendButton.gridy = 3;
        panel.add(sendButton, gbc_sendButton);

        JPanel panel_1 = new JPanel();
        GridBagConstraints gbc_panel_1 = new GridBagConstraints();
        gbc_panel_1.gridwidth = 4;
        gbc_panel_1.insets = new Insets(0, 0, 5, 5);
        gbc_panel_1.fill = GridBagConstraints.BOTH;
        gbc_panel_1.gridx = 0;
        gbc_panel_1.gridy = 4;
        panel.add(panel_1, gbc_panel_1);

        final JButton unBindButton = new JButton("解绑");
        unBindButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!DialogUtil.verifyTFEmpty(mobileTextField, "手机号")) {
                    return;
                }
                if (!DialogUtil.verifyTFEmpty(codeTextField, "短信验证码")) {
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String mobile = mobileTextField.getText();
                        try {
                            unBindButton.setEnabled(false);
                            boolean success = UnbindMobile.activeBind(codeTextField.getText2().trim(), ciaIpTextField.getText2());
                            getUnbindMobileBean().setMobile(mobile);
                            getUnbindMobileBean().setCiaDomain(ciaIpTextField.getText2());
                            unBindButton.setEnabled(true);
                            if (success) {
                                ToastMessage.toast(mobile + "解绑成功", 2000);
                            } else {
                                ToastMessage.toast(mobile + "解绑失败", 2000, Color.red);
                            }
                        } catch (IOException e1) {
                            e1.printStackTrace();
                            GUIUtil23.errorDialog(e1.getMessage());
                            unBindButton.setEnabled(true);
                        }
                    }
                }).start();
            }
        });
        panel_1.add(unBindButton);

        JScrollPane scrollPane = new JScrollPane();//增加边框
        GridBagConstraints gbc_scrollPane = new GridBagConstraints();
        gbc_scrollPane.gridwidth = 4;
        gbc_scrollPane.insets = new Insets(0, 0, 0, 5);
        gbc_scrollPane.fill = GridBagConstraints.BOTH;
        gbc_scrollPane.gridx = 0;
        gbc_scrollPane.gridy = 5;
        panel.add(scrollPane, gbc_scrollPane);

        noteTextPane = new AssistPopupTextPane();
        noteTextPane.setEditable(false);
        ComponentUtil.appendResult(noteTextPane, "集测环境请去 ", null, false);
        ComponentUtil.appendResult(noteTextPane, " http://172.16.200.65/#/ccp ", HTML_RED, false);
        ComponentUtil.appendResult(noteTextPane, "查看短信验证码", null, true);
        scrollPane.setViewportView(noteTextPane);
        DialogUtil.escape2CloseDialog(this);
    }

    /***
     * 判断手机号是否被占用
     * @param isRegisterbutton
     * @throws Exception
     */
    public void checkUserIdentify(JButton isRegisterbutton) throws Exception {
        HttpResponseResult resultArr;
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("{DES}/jVtMAHuT1k=", "{DES}fpNSygs55lpnVBj6rO7FzReAucFefdcfRD1JRNSpQ4SulZ/g5hvulg==");
        map.put("{DES}/OHatdRjVvGtaoi0+jeDPQ==", "{\"userIdentify\":\"" + mobileTextField.getText() + "\"}");
        String postData = ValueWidget.getRequestBodyFromMap(map, false);
        HttpRequestParameter httpRequestParameter = new HttpRequestParameter();
        httpRequestParameter.setUrl("http://" + ciaIpTextField.getText() + "/internal_api/v1/user/findUserByIdentify?" + postData)
                .setSsl(false)
                .setForcePost(true)
                .setSendData(postData)
                .setContentType(SystemHWUtil.CONTENTTYPE_JSON)
                .setRequestCharset(SystemHWUtil.CHARSET_UTF)
                .setConnectTimeout(45000)
                .setReadTimeout(45000);
        resultArr = HttpSocketUtil.httpRequest(httpRequestParameter);
        int respCode = resultArr.getResponseCode();
//        int resCode = respCode.intValue();
//                    ComponentUtil.appendResult(resultTextArea, "response code :" + resCode, true/*isAddDivide*/, false);
        byte[] resultJsonBytes = resultArr.getResponse();
        isRegisterbutton.setEnabled(true);
        /***
         * {"orgId":"","result":true,"orgIds":[],"username":"m_TLFY7OQQVmT","userChanjetId":"1189159","userId":"61000260736","emailBinding":"0","exists":"1","mobileBinding":"1","mobile":"17001098093","userType":"1"}
         <br>
         {"result":true,"exists":"0"}
         */
        String resultJson = new String(resultJsonBytes,
                SystemHWUtil.CHARSET_UTF);
//                    System.out.println(resultJson);
//                    ComponentUtil.appendResult(resultTextArea, JsonTool.formatJson(resultJson, "      "), true/*isAddDivide*/,false);
        if (respCode == 200 || respCode == 201) {
            Map responseMap = JSONHWUtil.getMap(resultJson);
            boolean result = (Boolean) responseMap.get("result");
            String exists = (String) responseMap.get("exists");
            String mesg;
            if (result && "1".equals(exists)) {
                String mobile = (String) responseMap.get("mobile");
                if (ValueWidget.isNullOrEmpty(mobile)) {
                    mobile = (String) responseMap.get("email");
                }
                mesg = "已被占用,账号为:" + mobile + ",userId:" + responseMap.get("userId");
                ComponentUtil.appendResult(noteTextPane, resultJson, HTML_GREEN, true);
                ToastMessage.toast(mesg, 2000);
            } else {
                mesg = "未被占用";
                ToastMessage.toast(mesg, 2000, Color.red);
            }
        } else {
            GUIUtil23.errorDialog("接口访问失败:" + resultJson);
        }
    }

    public void decideRadioSelected() {
        if (ciaIpTextField.getText().equals(CIA_DOMAIN_INTE)) {
            inteRadioButton.setSelected(true);
        } else if (ciaIpTextField.getText().equals(CIA_DOMAIN_PROD)) {
            productRadioButton.setSelected(true);
        }
    }

    public UnbindMobileBean getUnbindMobileBean() {
        return unbindMobileBean;
    }

    public void setUnbindMobileBean(UnbindMobileBean unbindMobileBean) {
        this.unbindMobileBean = unbindMobileBean;
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        Object source = e.getSource();
        if (e.getStateChange() == ItemEvent.SELECTED && source instanceof JRadioButton) {
            JRadioButton selectedRadio = (JRadioButton) source;
            if (selectedRadio == inteRadioButton) {
                ciaIpTextField.setText(CIA_DOMAIN_INTE);
            } else {
                ciaIpTextField.setText(CIA_DOMAIN_PROD);
            }
            if (null != codeTextField) {
                codeTextField.setText(SystemHWUtil.EMPTY);
            }
        }
    }
}
